﻿
Imports elpmis

Public Module lpmsrunr

    Public Const startFunctionName As String = "main"

    Private thread As Threading.Thread = Nothing

    Private Class threadParameters
        Public app As app = Nothing
        Public startFunctionName As String
        Public result As Boolean
    End Class

    Private Sub invokeThread(ByVal p As threadParameters)
        p.result = p.app.invoke(p.startFunctionName)
    End Sub

    Private Sub invokeThread(ByVal obj As Object)
        invokeThread(convertor.cast(Of threadParameters)(obj))
    End Sub

    Public Sub main(ByVal args() As String)
        If args Is Nothing OrElse args.Length() = 0 Then
            raiseError("usage, lpmsrunr {script_file}", errorHandle.errorType.user)
        Else
            counter.initial(counter.NOCOUNTERFILEMARK)
            startmain(logfile:=errorHandle.NOLOGFILEMARK)
            debugpause()
            Dim s As String = Nothing
            If Not readfile(args(0), s) Then
                raiseError("cannot read file " + args(0), errorHandle.errorType.user)
            ElseIf Not isemptystring(s) Then
                Dim app As app = Nothing
                If app.parse(s, 0, app) Then
                    Dim p As threadParameters = Nothing
                    p = New threadParameters()
                    p.app = app
                    If args.Length() > 1 Then
                        p.startFunctionName = args(1)
                    Else
                        p.startFunctionName = startFunctionName
                    End If
                    thread = startThread(AddressOf invokeThread, p)
                    While thread.IsAlive() AndAlso Not consoleExtSignal()
                        sleep(64)
                    End While
                    If consoleExtSignal() Then
                        raiseError("console cancel key caught, shutdown invoke thread.", errorHandle.errorType.user)
                        If thread.IsAlive() Then
                            thread.Abort()
                            p.result = True
                        End If
                    End If

                    If p.result Then
                        raiseError("success")
                    Else
                        raiseError("cannot invoke app " + args(0), errorHandle.errorType.user)
                    End If
                Else
                    raiseError("cannot parse file " + args(0), errorHandle.errorType.user)
                End If
            End If
        End If

        debugpause()
        finishmain()
    End Sub

End Module
